<!--
 * @Author: atdow
 * @Date: 2021-07-15 20:38:13
 * @LastEditors: luojiajun
 * @LastEditTime: 2021-07-27 19:59:08
 * @Description: file description
-->

<template>
    <div class="app-container">
        <div class="tree-title">
            <span>新建接口调用规则</span>
        </div>
        <el-form
            ref="ruleForm"
            :model="ruleForm"
            label-width="110px"
            :rules="rules"
            class="rule-form application-form clearfix"
        >
            <el-form-item label="规则名称" prop="ruleName">
                <el-input
                    v-model="ruleForm.ruleName"
                    placeholder="请输入规则名称"
                    clearable
                ></el-input>
            </el-form-item>
            <el-form-item label="限流方式" prop="ruleType">
                <el-select
                    style="width:100%"
                    v-model="ruleForm.ruleType"
                    placeholder="请选择限流方式"
                    clearable
                >
                    <el-option
                        v-for="item in ruleTypeList"
                        :label="item.name"
                        :value="item.id"
                        :key="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-row type="flex">
                <el-col>
                    <el-form-item label="限制规则" prop="limitRule">
                        <el-select
                            v-model="ruleForm.limitRule"
                            placeholder="请选择限制规则"
                            clearable
                        >
                            <el-option
                                v-for="item in limitRuleList"
                                :label="item.name"
                                :value="item.id"
                                :key="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col>
                    <el-form-item label="调用" prop="limitFrequency">
                        <el-input
                            v-model="ruleForm.limitFrequency"
                            placeholder="请输入调用次数"
                            class="float-left"
                            controls-position="right"
                            :min="0"
                            @keyup.native="number"
                            style="margin-right:10px;width:200px"
                        />
                        <span class="float-left">次</span>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="规则说明" prop="ruleDescription">
                <el-input
                    v-model="ruleForm.ruleDescription"
                    placeholder="请输入规则说明"
                    type="textarea"
                    clearable
                ></el-input>
            </el-form-item>
            <!-- <el-form-item
                label-width="15px"
                class="application-form-btn float-left"
            >
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="fetchData"
                    >查询</el-button
                >
                <el-button type="primary" size="mini" @click="resetForm"
                    >重置</el-button
                >
            </el-form-item> -->
        </el-form>
        <div class="tree-title">
            <span>需要限制的接口列表</span>
            <el-button
                class="m20"
                type="primary"
                size="mini"
                @click="dialogVisible = true"
                >编辑</el-button
            >
        </div>
        <el-table v-loading="tableLoading" :data="tableList" border>
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column
                label="URL地址"
                prop="requestPath"
                show-overflow-tooltip
                align="center"
            ></el-table-column>
            <el-table-column
                label="接口英文名称"
                prop="apiNameEn"
                show-overflow-tooltip
                align="center"
            >
            </el-table-column>
            <el-table-column
                label="接口名称"
                prop="apiName"
                show-overflow-tooltip
                align="center"
            >
            </el-table-column>
            <el-table-column
                label="接口版本号"
                prop="apiVersion"
                show-overflow-tooltip
                align="center"
            >
                <template slot-scope="scope">
                    {{ scope.row.apiVersion || "-" }}
                </template>
            </el-table-column>
            <!-- TODO -->
            <el-table-column
                label="所属分类"
                prop="groupName"
                show-overflow-tooltip
                align="center"
            >
                <template slot-scope="scope">
                    {{ scope.row.groupName || "-" }}
                </template>
            </el-table-column>
            <el-table-column
                label="创建人"
                prop="createBy"
                show-overflow-tooltip
                align="center"
            >
            </el-table-column>
            <el-table-column
                label="创建时间"
                prop="createTime"
                show-overflow-tooltip
                align="center"
            ></el-table-column>
        </el-table>
        <pagination
            v-show="totalNum > 0"
            :total="totalNum"
            :page.sync="page.pageNum"
            :limit.sync="page.pageSize"
            @pagination="fetchTableData"
        ></pagination>
        <el-row type="flex" justify="center" style="margin-top:20px">
            <el-button type="primary" :loading="editLoading" @click="edit"
                >确定</el-button
            >
            <el-button type="default" @click="cancel">取消</el-button>
        </el-row>

        <edit-api-list-modal
            v-model="dialogVisible"
            user-id="1"
            :defaultSelected="selected"
            @success="editApiListModalSuccess"
        />
    </div>
</template>

<script>
import EditApiListModal from "./modules/EditApiListModal.vue";
import {
    getLimitApiList,
    editLimitingRule,
    getEditLimitingRule
} from "@/api/dataService/serviceMonitor/throttlingList";
export default {
    name: "MineApplication",
    components: {
        EditApiListModal
    },
    data() {
        return {
            id: undefined,
            selected: [],
            ruleForm: {
                ruleName: undefined,
                ruleType: undefined,
                limitRule: undefined,
                limitFrequency: 0,
                ruleDescription: undefined
            },
            rules: {
                ruleName: [
                    {
                        required: true,
                        message: "请输入规则名称",
                        trigger: ["blur", "change"]
                    }
                ],
                ruleType: [
                    {
                        required: true,
                        message: "请输选址限流方式",
                        trigger: "change"
                    }
                ]
            },
            page: {
                pageNum: 1,
                pageSize: 10
            },
            limitFrequency: 0,
            ruleTypeList: [
                {
                    name: "接口限流",
                    id: 1
                },
                // {
                //     name: "ip限流",
                //     id: 2
                // }
            ],
            limitRuleList: [
                {
                    name: "不限",
                    id: 0
                },
                {
                    name: "年",
                    id: 1
                },
                {
                    name: "月",
                    id: 2
                },
                {
                    name: "周",
                    id: 3
                },
                {
                    name: "日",
                    id: 4
                },
                {
                    name: "时",
                    id: 5
                },
                {
                    name: "分",
                    id: 6
                },
                {
                    name: "秒",
                    id: 7
                }
            ],
            groupList: [],
            pickerOptions: {},
            tableLoading: false,
            tableList: [],
            totalNum: 0,
            dialogVisible: false,

            editLoading: false
        };
    },
    created() {
        // 编辑模式
        this.id = this.$route.query.id;
        if (this.id === undefined) {
            return;
        }
        getEditLimitingRule({
            limitingId: this.id
        }).then(res => {
            if (res.code !== 200) {
                return;
            }
            const {
                ruleName,
                ruleType,
                limitRule,
                limitFrequency = 0,
                ruleDescription,
                apiIds = []
            } = res.data;
            this.ruleForm = {
                ruleName,
                ruleType,
                limitRule,
                limitFrequency: limitFrequency || 0,
                ruleDescription
            };
            this.selected = apiIds;
            if (this.selected && this.selected.length > 0) {
                this.page = {
                    pageNum: 1,
                    pageSize: 10
                };
                this.fetchTableData();
            }
        });
    },
    activated() {},
    methods: {
        number() {
            this.ruleForm.limitFrequency = this.ruleForm.limitFrequency.replace(
                /[^\.\d]/g,
                ""
            );
            this.ruleForm.limitFrequency = this.ruleForm.limitFrequency.replace(
                ".",
                ""
            );
        },
        handleClick(value) {
            this.$refs.throttlingListTableRef.fetchData();
        },
        changeDatetimePicker(data) {
            let startTime = "",
                endTime = "";
            if (data && data.length) {
                startTime = this.parseTime(
                    new Date(data[0]),
                    "{y}-{m}-{d} {h}:{i}:{s}"
                );
                endTime = this.parseTime(
                    new Date(data[1]),
                    "{y}-{m}-{d} {h}:{i}:{s}"
                );
            }
            this.ruleForm.startTime = startTime;
            this.ruleForm.endTime = endTime;
        },
        resetForm() {
            this.$refs.ruleForm.resetFields();
        },
        fetchData() {},
        handleClose(done) {
            this.$confirm("确认关闭？")
                .then(_ => {
                    done();
                })
                .catch(_ => {});
        },
        editApiListModalSuccess(selected = []) {
            this.page = {
                pageNum: 1,
                pageSize: 10
            };
            this.selected = selected;
            this.fetchTableData();
        },
        fetchTableData() {
            getLimitApiList(this.selected, this.page)
                .then(res => {
                    if (res.code == 200) {
                        this.tableList = res.data.records;
                        this.totalNum = res.data.total;
                    }
                })
                .catch(err => {})
                .finally(() => {});
        },
        edit() {
            this.$refs.ruleForm.validate((boolean, object) => {
                if (boolean !== true) {
                    return;
                }
                if (this.selected.length === 0) {
                    this.$message.warning("选择需要限制的接口");
                    return;
                }
                this.editLoading = true;
                let parmas = {
                    apiIds: this.selected,
                    ...this.ruleForm,
                    limitFrequency: Number(this.ruleForm.limitFrequency)
                };
                if (this.id !== undefined) {
                    parmas.id = this.id;
                }
                editLimitingRule(parmas)
                    .then(res => {
                        // console.log("res:", res);
                        if (res.code !== 200) {
                            this.$message.error("新建失败");
                            return;
                        } else {
                            this.$message.success("新建成功");
                            this.$router.back();
                        }
                    })
                    .catch(err => {})
                    .finally(() => {
                        this.editLoading = false;
                    });
            });
        },
        cancel() {
            this.$router.back();
        }
    }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/system/tree.scss";
.app-container {
    padding: 20px;

    .application-form ::v-deep {
        .el-form-item__label {
            text-align: right;
        }
    }
    .rule-form {
        width: 680px;
    }
}
</style>
